package com.yimi.yinhepda.views.createPackage_module;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import butterknife.Bind;

import com.pda.ym.utils.SysInfo;
import com.yimi.yinhepda.R;
import com.yimi.yinhepda.adapter.BuildPackageScanAdapter;
import com.pda.ym.callbacks.UICallBack;
import com.yimi.yinhepda.db.dao.BuildPckScanTableDao;
import com.yimi.yinhepda.db.table.BuildPckScanTable;
import com.yimi.yinhepda.entity.request.BuildPckDetailRequest;
import com.yimi.yinhepda.entity.request.BuildPckUploadRequest;
import com.yimi.yinhepda.entity.request.QueryWaybillByChildNoRequest;
import com.yimi.yinhepda.entity.response.BuildPackUploadResponse;
import com.yimi.yinhepda.entity.response.BuildPackageDetailResponse;
import com.yimi.yinhepda.entity.response.QueryWaybillByChildNoResponse;
import com.yimi.yinhepda.entity.response.WaybillInfo;
import com.yimi.yinhepda.event.CountEvent;
import com.pda.ym.net.NetRequest;
import com.yimi.yinhepda.utils.Common;
import com.pda.ym.utils.Constants;
import com.yimi.yinhepda.utils.IntentUtils;
import com.pda.uce.commom.util.MyDialog;
import com.pda.ym.utils.SharedPreferUtil;
import com.pda.ym.utils.SoundVibratorManager;
import com.pda.ym.utils.StringUtils;
import com.yimi.yinhepda.base.BaseInitActivity;
import com.yimi.yinhepda.utils.ScrollTextView;
import com.yimi.yinhepda.views.load_module.DetailsActivity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * 建包扫描界面
 *
 * @author tianjin
 */
public class CreatePackageScanActivity extends BaseInitActivity {

    private static final String TAG = "CreatePackageScanActivi";
    /**
     * 标题栏左边
     */
    @Bind(R.id.title)
    TextView mTvTitle;
    /**
     * 标题栏中间
     */
    @Bind(R.id.num)
    TextView mTvNum;
    /**
     * 标题栏右边
     */
    @Bind(R.id.next_station)
    ScrollTextView mTvNextStation;
    /**
     * 返回按钮
     */
    @Bind(R.id.scan_back)
    Button mTvBack;
    /**
     * 完成按钮
     */
    @Bind(R.id.scan_complete)
    Button mTvComplete;
    /**
     * 暂存按钮
     */
    @Bind(R.id.package_scan_temp_save)
    Button mTvTempSave;
    /**
     * 列表
     */
    @Bind(R.id.create_package_scan_listview)
    ListView mListView;
    /**
     * 总票
     */
    @Bind(R.id.totle_piao)
    TextView mTvTotlePiao;
    /**
     * 总件
     */
    @Bind(R.id.totle_jian)
    TextView mTvTotleJian;
    /**
     * 实操票
     */
    @Bind(R.id.hold_piao)
    TextView mTvHoldPiao;
    /**
     * 实操件
     */
    @Bind(R.id.hold_jian)
    TextView mTvHoldJian;
    @Bind(R.id.btn_add)
    Button mBtnAdd;
    @Bind(R.id.btn_del)
    Button mBtnDel;
    /**
     * 建包目的地
     */
    private String destCode;
    private String destName;
    private BuildPackageScanAdapter buildPackageScanAdapter;

    /**
     * 建包运单号号的集合 --- 全局的--- 手动添加，撤销都使用它, 但是注意释放
     */
    public static List<BuildPackageDetailResponse.StockInfo> buildList;

    /**
     * 操作数据库的对象
     */
    private BuildPckScanTableDao mBuildPckScanTableDao;
    /**
     * 当前扫描数据插入到数据库的集合，方便后期删除
     */
    private List<BuildPckScanTable> mBuildTableDaoList = new ArrayList<>();
    /**
     * 总的未上传数量
     */
    private int totalNotUploadNum;
    /**
     * 任务号
     */
    private String taskNo;

    public static final int BUILD_RESULT = 101;

    public CreatePackageScanActivity() {
        super(true);
    }

    @Override
    public String getPageName() {
        return getString(R.string.page_create_scan);
    }

    @Override
    public int getContentViewId() {
        return R.layout.activity_create_package_scan;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        mTvTitle.setText(getString(R.string.createPack_title));
        //下个目的地
        destCode = getIntent().getStringExtra(IntentUtils.BUILD_DEST);
        destName = getIntent().getStringExtra(IntentUtils.BUILD_DEST_NAME);
        Log.d(TAG, "initView: 当前目的地=" + SharedPreferUtil.getInstance().getValue(Common.DEPT_CODE) + ", 目标目的地=" + destCode + ",名字=" + destName);
        mTvNextStation.setText(destName);
        //获取任务号
        taskNo = getIntent().getStringExtra(IntentUtils.BUILD_PKG_TASK_NO);
        //EventBus注册
        EventBus.getDefault().register(this);
    }

    @Override
    public void initData() {
        //新建列表
        buildList = new ArrayList<>();
        buildPackageScanAdapter = new BuildPackageScanAdapter(this, buildList);
        mListView.setAdapter(buildPackageScanAdapter);

        /** 查询未上传数据*/
        mBuildPckScanTableDao = new BuildPckScanTableDao();
        totalNotUploadNum = mBuildPckScanTableDao.queryNotUploadDataNum(taskNo);
        mTvNum.setText(totalNotUploadNum + "");

        //访问接口
        loadData();
    }

    @Override
    public void initEvent() {
        mBtnAdd.setOnClickListener(this);
        mBtnDel.setOnClickListener(this);
        mTvBack.setOnClickListener(this);
        mTvComplete.setOnClickListener(this);
        mTvTempSave.setOnClickListener(this);
        // 获取主单对应的子单
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View view, int position, long arg3) {
                Intent intent = new Intent(CreatePackageScanActivity.this, CreateWayBillDetailActivity.class);
                intent.putExtra(IntentUtils.BUILD_WAYBILLNO, buildList.get(position).getWaybillNo());
                startActivityForResult(intent, 0);
            }
        });
        // 长按listview进入子单
        mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
                String waybill = buildList.get(position).getWaybillNo();
                Intent intent = new Intent(CreatePackageScanActivity.this, DetailsActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("waybill", waybill);
                intent.putExtras(bundle);
                startActivity(intent);
                return true;
            }
        });
    }

    /**
     * 加载接口数据
     */
    public void loadData() {
        //关闭扫描
        setScannerEnabled(false);
        showPgDlg("正在加载...");
        new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                .setUrl(Constants.URL_CREATE_PACKAGE_LOAD_SCAN)
                .setRequestObject(new BuildPckDetailRequest(SharedPreferUtil.getInstance().getValue(Common.DEPT_CODE), destCode))
                .setResponsClazz(BuildPackageDetailResponse.class)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {

                        if (msg != null) {
                            showToast(msg);
                        } else {
                            showToast("服务器出错了!");
                        }

                        SoundVibratorManager.playSound(2);
                        dismissPgDlg();
                        setScannerEnabled(true);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        BuildPackageDetailResponse response = (BuildPackageDetailResponse) obj;
                        if (response.getData() == null || response.getData().size() <= 0) {
                            showToast("接口返回没有数据!");
                            SoundVibratorManager.playSound(2);
                        } else {
                            showDataDetail(response);
                            SoundVibratorManager.playSound(1);
                        }
                        dismissPgDlg();
                        setScannerEnabled(true);
                    }
                });
    }

    /**
     * listview 加载数据
     */
    public void showDataDetail(BuildPackageDetailResponse response) {

        buildList = response.getData();
        //与本地数据合并
        mergeLocalData();

        // 对刷新的列表重新进行排序
        Collections.sort(buildList);

        //加载到列表
        buildPackageScanAdapter = new BuildPackageScanAdapter(this, buildList);
        mListView.setAdapter(buildPackageScanAdapter);

        showCountNum();
    }

    private void mergeLocalData() {
        //查询本地暂存数据的设置为已扫描
        List<BuildPckScanTable> beans = mBuildPckScanTableDao.getDataByTaskNo(taskNo);
        for (BuildPckScanTable bean : beans) {
            boolean isExistWaybill = false;
            for (BuildPackageDetailResponse.StockInfo stockInfo : buildList) {
                if (bean.getWaybillNo().equals(stockInfo.getWaybillNo())) {
                    isExistWaybill = true;
                    boolean isExist = false;
                    for (BuildPackageDetailResponse.ChildInfo childInfo : stockInfo.getChildList()) {
                        if (bean.getChildWaybillNo().equals(childInfo.getChildWaybillNo())) {
                            //设置已扫
                            childInfo.setFlag(1);
                            isExist = true;
                            break;
                        }
                    }
                    if (!isExist) {
                        BuildPackageDetailResponse.ChildInfo childInfo = new BuildPackageDetailResponse.ChildInfo();
                        childInfo.setChildWaybillNo(bean.getChildWaybillNo());
                        //设置已扫
                        childInfo.setFlag(1);
                        stockInfo.getChildList().add(childInfo);
                    }
                    break;
                }
            }
            if (!isExistWaybill) {
                buildList.add(mergeData(bean));
            }
        }
    }

    /**
     * 合并数据到内存
     */
    private BuildPackageDetailResponse.StockInfo mergeData(BuildPckScanTable bean) {

        BuildPackageDetailResponse.StockInfo stockInfo = new BuildPackageDetailResponse.StockInfo();
        stockInfo.setWaybillNo(bean.getWaybillNo() + "");
        stockInfo.setPackageNo("");
        stockInfo.setSrcPiecesNum(bean.getSrcPiecesNum());
        stockInfo.setPiecesNum(bean.getPiecesNum());
        stockInfo.setWeight(bean.getWeight());
        stockInfo.setChargedWeight(bean.getChargedWeight());
        stockInfo.setVolume(bean.getVolume());
        stockInfo.setAreaCode("");
        stockInfo.setBillType("");
        stockInfo.setWaybillRoute(bean.getRoute());
        stockInfo.setRemark("2");

        List<BuildPackageDetailResponse.ChildInfo> childList = new ArrayList<BuildPackageDetailResponse.ChildInfo>();
        BuildPackageDetailResponse.ChildInfo mChildInfo = new BuildPackageDetailResponse.ChildInfo();
        mChildInfo.setFlag(1);
        mChildInfo.setChildWaybillNo(bean.getChildWaybillNo());
        childList.add(mChildInfo);
        //子单集合加入到运单对象中
        stockInfo.setChildList(childList);
        return stockInfo;
    }

    private void showCountNum() {
        //总票，总件
        mTvTotlePiao.setText(buildList.size() + "");
        mTvTotleJian.setText(BuildPackageDetailResponse.getTotaljian(buildList) + "");

        //实操票，实操件
        mTvHoldPiao.setText(BuildPackageDetailResponse.getHoldpiao(buildList) + "");
        mTvHoldJian.setText(BuildPackageDetailResponse.getHoldjian(buildList) + "");
    }

    /**
     * 巴枪扫描广播回调方法
     *
     * @param result 条码
     */
    @Override
    protected void handleBarCode(String result) {
        super.handleBarCode(result);
        if (result == null) {
            SoundVibratorManager.playSound(2);
        } else {
            startDealScanResult(result);
        }
    }

    /**
     * 巴枪扫描完成，返回处理条码，刷新列表，显示扫描数量
     */
    private void startDealScanResult(String result) {
        //判断单号长度
        if (!StringUtils.isWaybillNo(result)) {
            SoundVibratorManager.playSound(2);
            showToast("运单号不规范");
            return;
        }
        /**
         * 将扫描的单子和总数据对比，是否存在
         */
        if (buildList == null) {
            buildList = new ArrayList<>();
        }

        for (int i = 0; i < buildList.size(); i++) {

            //当前行的运单信息，包括子单的集合
            BuildPackageDetailResponse.StockInfo currentItemInfo = buildList.get(i);
            //判断子单是不是以主单开始的,减少循环次数
            if (!result.startsWith(currentItemInfo.getWaybillNo())) {
                continue;
            }

            //子单的集合
            List<BuildPackageDetailResponse.ChildInfo> childList = currentItemInfo.getChildList();
            //循环子单的集合
            for (BuildPackageDetailResponse.ChildInfo child : childList) {
                //子单字符串
                String childWaybillno = child.getChildWaybillNo();
                //扫描子单和集合中一个子单相同
                if (result.equals(childWaybillno)) {
                    Integer flag = child.getFlag();

                    if (flag == 1) {
                        SoundVibratorManager.playSound(2);
                        showToast("重复扫描!");
                    } else {
                        String remark = "1";
                        if (currentItemInfo.getRemark() != null) {
                            if (currentItemInfo.getRemark().equals("2")) {
                                remark = "2";
                            }
                        }
                        /** 扫描数据插入到表中*/
                        if (insertScannedData(currentItemInfo, childWaybillno, remark) < 0) {
                            SoundVibratorManager.playSound(2);
                            showToast("插入数据库失败!");
                            return;
                        }
                        //未上传数据
                        totalNotUploadNum++;
                        mTvNum.setText(totalNotUploadNum + "");
                        EventBus.getDefault().post(new CountEvent(totalNotUploadNum));

                        /** 设置该子单为已扫描的状态*/
                        child.setFlag(1);
                        SoundVibratorManager.playSound(1);

                        /** 刷新增加，减少(撤销的)实操票和件*/
                        mTvHoldPiao.setText(BuildPackageDetailResponse.getHoldpiao(buildList) + "");
                        mTvHoldJian.setText(BuildPackageDetailResponse.getHoldjian(buildList) + "");
                    }

                    /** 更新当前行到第一行*/
                    buildList.remove(i);
                    /**排序按照颜色：红，白，绿*/
                    Collections.sort(buildList);
                    buildList.add(0, currentItemInfo);
                    /** 刷新列表*/
                    buildPackageScanAdapter.notifyDataSetChanged();
                    showCountNum();
                    return;
                }
            }
        }

        SoundVibratorManager.playSound(2);
        showToast("运单号不在列表中！");

        /** 条码不在任务内, 后面进行路由判断，是否强扫*/
        //downloadWaybillNo(result);
    }

    /**
     * 子单下载主单
     */
    private void downloadWaybillNo(final String result) {
        setScannerEnabled(false);
        showPgDlg("正在子单下载主单...");

        //扫描数据上传完后  调完成任务
        QueryWaybillByChildNoRequest mQueryWaybillByChildNoRequest = new QueryWaybillByChildNoRequest();
        mQueryWaybillByChildNoRequest.setChildWaybillNo(result);

        Map param = new HashMap();
        param.put("childWaybillNo", result);
        new NetRequest().setMethod(NetRequest.Method.GET)
                .setRequestObject(mQueryWaybillByChildNoRequest)
                .setUrl(Constants.URL_FORCE_SCAN)
                .setParams(param)
                .setResponsClazz(QueryWaybillByChildNoResponse.class)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        dismissPgDlg();
                        SoundVibratorManager.playSound(2);
                        if (msg != null) {
                            showToast("子单下载主单失败:" + msg);
                        } else {
                            showToast("子单下载主单失败!");
                        }

                        setScannerEnabled(true);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        final QueryWaybillByChildNoResponse response = (QueryWaybillByChildNoResponse) obj;
                        //路由验证
                        if (!Common.waybillRouteWrong(response.getData().getRouteCode(), destCode)) {
                            //合并数据到内存，并插入当前条码到数据库
                            merge(response.getData(), result);
                        } else {
                            MyDialog dialog = new MyDialog(CreatePackageScanActivity.this);
                            dialog.setIcon(R.drawable.alert);
                            dialog.setDialogType(MyDialog.DialogType.ALERT_DIALOG);
                            dialog.setTitle("系统提示");
                            dialog.setMessage("请核对正确目的站是否扫描？");
                            dialog.setPositiveClickListener("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                    //合并数据到内存，并插入当前条码到数据库
                                    merge(response.getData(), result);
                                }
                            });
                            dialog.setNegativeClickListener(R.drawable.btn_login_selector, "取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            });
                            dialog.show();
                        }
                        //开启扫描
                        setScannerEnabled(true);
                        dismissPgDlg();
                    }
                });
    }

    /**
     * 合并数据到内存，并插入当前条码到数据库
     */
    private void merge(WaybillInfo data, String result) {

        BuildPackageDetailResponse.StockInfo stockInfo = new BuildPackageDetailResponse.StockInfo();
        stockInfo.setWaybillNo(data.getWaybillNo() + "");
        stockInfo.setPackageNo("");
        stockInfo.setSrcPiecesNum(data.getQuantity());
        stockInfo.setPiecesNum(data.getNowInventory());
        stockInfo.setWeight(data.getRealWeight());
        stockInfo.setChargedWeight(data.getChargeableWeight());
        stockInfo.setVolume(data.getVolume());
        stockInfo.setAreaCode("");
        stockInfo.setBillType("");
        stockInfo.setWaybillRoute(data.getRouteCode());
        stockInfo.setRemark("2");

        List<BuildPackageDetailResponse.ChildInfo> childList = new ArrayList<BuildPackageDetailResponse.ChildInfo>();
        for (int i = 0; i < data.getQuantity(); i++) {
            String childWaybillNo = data.getWaybillNo() + String.format("%03d", i + 1);
            BuildPackageDetailResponse.ChildInfo mChildInfo = new BuildPackageDetailResponse.ChildInfo();
            if (result.equals(childWaybillNo)) {
                mChildInfo.setFlag(1);
            } else {
                mChildInfo.setFlag(0);
            }
            mChildInfo.setChildWaybillNo(childWaybillNo);
            childList.add(mChildInfo);
        }
        //子单集合加入到运单对象中
        stockInfo.setChildList(childList);

        //强扫去除重复运单
        Iterator<BuildPackageDetailResponse.StockInfo> it = buildList.iterator();
        while (it.hasNext()) {
            BuildPackageDetailResponse.StockInfo stockInfo1 = it.next();
            if (stockInfo1.getWaybillNo().equals(data.getWaybillNo().toString())) {
                stockInfo.setPiecesNum(stockInfo1.getPiecesNum());
                it.remove();
                break;
            }
        }

        //扫描的子单插入到数据库
        if (insertScannedData(stockInfo, result, "2") < 0) {
            SoundVibratorManager.playSound(2);
            showToast("插入数据失败!");
            return;
        }

        //未上传数据
        totalNotUploadNum++;
        mTvNum.setText(totalNotUploadNum + "");

        SoundVibratorManager.playSound(1);

        buildList.add(0, stockInfo);

        //与本地数据合并
        mergeLocalData();
        // 对刷新的列表重新进行排序
        Collections.sort(buildList);
        buildPackageScanAdapter.notifyDataSetChanged();
        showCountNum();
    }

    /**
     * 插入已经扫描的数据到表中
     *
     * @param currentItemInfo 当前运单号的相关信息
     * @param childWaybillNo  当前子单的相关信息
     */
    private int insertScannedData(BuildPackageDetailResponse.StockInfo currentItemInfo, String childWaybillNo, String remark) {

        BuildPckScanTable buildPckScanTable = new BuildPckScanTable();
        //开单件数
        buildPckScanTable.setSrcPiecesNum(currentItemInfo.getSrcPiecesNum());
        //库存件数
        buildPckScanTable.setPiecesNum(currentItemInfo.getPiecesNum());
        //开单重量
        buildPckScanTable.setWeight(currentItemInfo.getWeight());
        //开单体积
        buildPckScanTable.setVolume(currentItemInfo.getVolume());
        //计费重量
        buildPckScanTable.setChargedWeight(currentItemInfo.getChargedWeight());
        buildPckScanTable.setTaskNo(taskNo);
        buildPckScanTable.setPackageNo(currentItemInfo.getPackageNo());
        //目的地编号
        buildPckScanTable.setDestDeptCode(destCode);
        //目的地名称
        buildPckScanTable.setDestDeptName(destName);
        //当前站点编号
        buildPckScanTable.setSrcDeptCode(SharedPreferUtil.getInstance().getValue(Common.DEPT_CODE));
        //当前站点名称
        buildPckScanTable.setSrcDeptName(SharedPreferUtil.getInstance().getValue(Common.DEPT_NAME));
        //路由
        buildPckScanTable.setRoute(currentItemInfo.getWaybillRoute());
        //操作人员工号
        buildPckScanTable.setOperEmpCode(SharedPreferUtil.getInstance().getValue(Common.USER_CODE));
        //操作人员姓名
        buildPckScanTable.setOperEmpName(SharedPreferUtil.getInstance().getValue(Common.USER_NAME));
        //数据库时间, 3天
        buildPckScanTable.setOperTime(Constants.GetSysTime());
        //扫描时间,
        buildPckScanTable.setScanTime(Constants.GetScanTime());
        //主单号
        buildPckScanTable.setWaybillNo(currentItemInfo.getWaybillNo());
        //子单号
        buildPckScanTable.setChildWaybillNo(childWaybillNo);
        //装卸车类型  操作类型，操作码:3 -装包??
        buildPckScanTable.setOperTypeCode(0);
        //输入方式 1-PDA扫描输入,2-手动输入
        buildPckScanTable.setInputType(1);
        //强扫标记 或者备注??
        buildPckScanTable.setRemark(remark);
        //到达库区
        buildPckScanTable.setAreaCode(currentItemInfo.getAreaCode());
        //所属网点
        buildPckScanTable.setDeptCode(SharedPreferUtil.getInstance().getValue(Common.DEPT_CODE));
        buildPckScanTable.setDeviceCode(SysInfo.getInstance().getImei());
        buildPckScanTable.setIsUpload(0);

        mBuildTableDaoList.add(buildPckScanTable);
        int result = -1;
        try {
            result = mBuildPckScanTableDao.insert(buildPckScanTable);
        } catch (Exception e) {
            e.printStackTrace();
            result = -1;
        }
        return result;
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        Intent intent;
        switch (v.getId()) {
            case R.id.scan_back:
                //返回按钮
                MyDialog backDialog = new MyDialog(CreatePackageScanActivity.this);
                backDialog.setIcon(R.drawable.alert);
                backDialog.setMessage("放弃此次建包数据,确定退出？");
                backDialog.setPositiveClickListener( Constants.confirmMsg, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //清除表中的数据
                        try {
                            mBuildPckScanTableDao.delelteByTaskNo(taskNo);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        dialog.dismiss();
                        finish();
                    }
                });
                backDialog.setNegativeClickListener(R.drawable.btn_cancel_selector, Constants.cancelMsg, null);
                backDialog.show();
                break;
            case R.id.scan_complete:
                if (buildList == null || buildList.size() <= 0) {
                    showToast("无扫描的运单！");
                    return;
                }
                if (!isLoadScan(buildList)) {
                    showToast("无扫描的运单！");
                    return;
                }
                //完成按钮
                MyDialog myDialog = new MyDialog(CreatePackageScanActivity.this);
                myDialog.setIcon(R.drawable.alert);
                myDialog.setMessage("提交后将完成扫描，是否提交？");
                myDialog.setPositiveClickListener( Constants.confirmMsg, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        completeScanUploadData();
                        dialog.dismiss();
                    }
                });
                myDialog.setNegativeClickListener(R.drawable.btn_cancel_selector, Constants.cancelMsg, null);
                myDialog.show();
                break;
            case R.id.btn_add:
                //添加按钮
                intent = new Intent(CreatePackageScanActivity.this, CreateAddByHandActivity.class);
                intent.putExtra(IntentUtils.BUILD_PKG_TASK_NO, taskNo);
                intent.putExtra(IntentUtils.BUILD_DEST, destCode);
                intent.putExtra(IntentUtils.BUILD_DEST_NAME, destName);
                startActivityForResult(intent, 0);
                break;
            case R.id.btn_del:
                //删除按钮
                intent = new Intent(CreatePackageScanActivity.this, CreateDeleteByHandActivity.class);
                intent.putExtra(IntentUtils.BUILD_PKG_TASK_NO, taskNo);
                intent.putExtra(IntentUtils.BUILD_DEST, destCode);
                intent.putExtra(IntentUtils.BUILD_DEST_NAME, destName);
                startActivityForResult(intent, 0);
                break;
            case R.id.package_scan_temp_save:
                if (buildList == null || buildList.size() <= 0) {
                    showToast("无扫描的运单！");
                    return;
                }
                if (!isLoadScan(buildList)) {
                    showToast("无扫描的运单！");
                    return;
                }
                //暂存按钮
                intent = new Intent(this, CreatePackageTaskTempSaveList.class);
                startActivity(intent);
                finish();
                break;
            default:
                break;
        }
    }

    protected boolean isLoadScan(List<BuildPackageDetailResponse.StockInfo> list) {
        Iterator it = list.iterator();
        while (it.hasNext()) {
            BuildPackageDetailResponse.StockInfo stockInfo = (BuildPackageDetailResponse.StockInfo) it.next();
            if (stockInfo.getChildList() != null && stockInfo.getChildList().size() > 0) {
                for (BuildPackageDetailResponse.ChildInfo item : stockInfo.getChildList()) {
                    //查询单号是否扫描
                    if (item.getFlag() == 1) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /**
     * 扫描完成,提交数据，到接口
     */
    public void completeScanUploadData() {

        setScannerEnabled(false);
        showPgDlg("正在提交...");

        //获取未上传的数据，然后判断
        final List<BuildPckScanTable> unUploadList = mBuildPckScanTableDao.getUnUploadDataList(taskNo);
        if (unUploadList == null || unUploadList.size() <= 0) {
            dismissPgDlg();
            setScannerEnabled(true);
            showToast("没有未上传的数据!");
            return;
        }

        //上传的json对象
        BuildPckUploadRequest buildPckUploadRequest = getBuildUploadData(unUploadList);

        new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                .setRequestObject(buildPckUploadRequest)
                .setResponsClazz(BuildPackUploadResponse.class)
                .setUrl(Constants.URL_CREATE_PACKAGE_UPLOAD_SCAN)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        if (msg != null) {
                            showToast(msg);
                        } else {
                            showToast("服务器出错了!");
                        }

                        dismissPgDlg();
                        setScannerEnabled(true);
                        SoundVibratorManager.playSound(2);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        BuildPackUploadResponse response = (BuildPackUploadResponse) obj;
                        //未上传数量改变
                        totalNotUploadNum = 0;
                        mTvNum.setText(totalNotUploadNum + "");

                        //更新未上传字段为已上传
                        for (BuildPckScanTable itemTable : unUploadList) {
                            itemTable.setStatus(1);
                            itemTable.setIsUpload(1);
                            mBuildPckScanTableDao.updataItem(itemTable);
                        }

                        showToast("提交完成!");
                        dismissPgDlg();
                        //跳转到完成页面
                        startToCompleteActivity(response);
                    }
                });
    }

    /**
     * //跳转到完成页面
     */
    private void startToCompleteActivity(BuildPackUploadResponse response) {
        Intent intent = new Intent(CreatePackageScanActivity.this, CreatePackageCompleteActivity.class);
        intent.putExtra(IntentUtils.PACKAGENO, response.getData().getPackageNo());
        //包的重量和体积要进行计算和
        intent.putExtra(IntentUtils.PACKAGEWEIGHT, response.getData().getWeight() + "");
        intent.putExtra(IntentUtils.PACKAGEVOLUME, response.getData().getVolume() + "");
        intent.putExtra(IntentUtils.TOTALPIAO, response.getData().getPriceNum() + "");
        intent.putExtra(IntentUtils.BUILD_DEST, destName);
        startActivity(intent);

        //静态变量清空
        buildList = null;
        finish();
    }

    /***
     * 准备上传的数据对象
     *
     * @param unUploadList 数据库中未上传的数据集合
     */
    private BuildPckUploadRequest getBuildUploadData(List<BuildPckScanTable> unUploadList) {

        Log.d(TAG, "initView: 当前目的地=" + unUploadList.get(0).getSrcDeptCode() + ", 目标目的地=" + destCode + ",名字=" + destName);

        /** 上传需要的总对象*/
        BuildPckUploadRequest mUploadBean = new BuildPckUploadRequest();
        mUploadBean.setPackageNo(unUploadList.get(0).getPackageNo());
        mUploadBean.setSrcDeptCode(unUploadList.get(0).getSrcDeptCode());
        mUploadBean.setSrcDeptName(unUploadList.get(0).getSrcDeptName());
        mUploadBean.setDestDeptCode(destCode);
        mUploadBean.setDestDeptName(destName);
        //该路由不能是第一票强扫的
        mUploadBean.setRoute(buildList.get(0).getWaybillRoute());
        mUploadBean.setOperEmpCode(unUploadList.get(0).getOperEmpCode());
        mUploadBean.setOperEmpName(unUploadList.get(0).getOperEmpName());
        mUploadBean.setScanTime(unUploadList.get(0).getScanTime());

        /** 扫描信息的集合*/
        List<BuildPckUploadRequest.ScanDetailEntity> scanDetailList = new ArrayList<>();
        for (BuildPckScanTable itemTable : unUploadList) {
            //扫描信息
            BuildPckUploadRequest.ScanDetailEntity scanDetailEntity = new BuildPckUploadRequest.ScanDetailEntity();
            scanDetailEntity.setWaybillNo(itemTable.getWaybillNo());
            scanDetailEntity.setChildWaybillNo(itemTable.getChildWaybillNo());
            //装卸车类型  操作类型，操作码:3 -装包
            scanDetailEntity.setOperTypeCode(itemTable.getOperTypeCode());
            //输入方式 1-PDA扫描输入,2-手动输入
            scanDetailEntity.setInputType(itemTable.getInputType());
            //强扫标记 或者备注
            scanDetailEntity.setRemark(itemTable.getRemark());
            //到达库区
            scanDetailEntity.setAreaCode(itemTable.getAreaCode());
            //所属网点
            scanDetailEntity.setDeptCode(itemTable.getDeptCode());
            scanDetailEntity.setDeviceCode(itemTable.getDeviceCode());
            //上传时间
            scanDetailEntity.setScanTime(itemTable.getScanTime());
            scanDetailList.add(scanDetailEntity);
        }
        mUploadBean.setRecords(scanDetailList);
        return mUploadBean;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (buildPackageScanAdapter != null) {
            //与本地数据合并
            mergeLocalData();
            // 对刷新的列表重新进行排序
            Collections.sort(buildList);
            buildPackageScanAdapter.notifyDataSetChanged();
            showCountNum();
            totalNotUploadNum = mBuildPckScanTableDao.queryNotUploadDataNum(taskNo);
            mTvNum.setText(totalNotUploadNum + "");
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMainEventBus(CountEvent countEvent) {
        Log.e("", "event---->" + countEvent.getCount());
        mTvNum.setText(countEvent.getCount() + "");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (buildList != null) {
            buildList.clear();
            buildList = null;
        }
        EventBus.getDefault().unregister(this);
    }
}
